module.exports = (config, ddd) => {
  console.log(config);
  var express = require("express");
  var router = express.Router();

  const openapi = require("@alicloud/openapi-client");
  const dysms = require("@alicloud/dysmsapi20170525");
  const openapi_config = new openapi.Config({
    accessKeyId: config.aliyun.accessKeyId,
    accessKeySecret: config.aliyun.accessKeySecret,
  });

  const smsClient = new dysms.default({
    ...openapi_config,
    endpoint: config.aliyun.sms.endpoint,
  });

  router.get("/", (req, res) => {
    // res.render("login/login", { title: "Xinbo Login" });
    res.json({ title: "Xinbo Login" });
  });

  router.post("/byphone", async function (req, res, next) {
    console.log({ login_check: req.body });
    let phone = req.body.phone,
      code = req.body.code;

    let storedcode = await ddd.getRedis("verifycode:".concat(phone));
    if (storedcode !== code) {
      // res.render("login/error", {
      //   title: "登录错误",
      //   message: "手机号或验证码无效。",
      // });
      res.json({ title: "登录错误", message: "手机号或验证码无效。" });
    } else {
      let profile = await ddd.exec({
        sp: "auth_profile",
        data: { phone },
      });

      console.log({ pos: "login/byphone", profile });

      if (profile.uid > 0) {
        let token = tokenCreate();
        await ddd.setRedis(
          "token:".concat(token),
          JSON.stringify(profile),
          config.cookieexpire
        );

        console.log(token, profile);
        // res.cookie("token", token, { maxAge: 6 * 3600 * 1000, domain: ".51marine.com", secure: true, sameSite: "none" }); //SSL请求时候设置
        let cookieOptions = {
          maxAge: config.cookieexpire * 1000,
          domain: config.cookiedomain,
        };
        res.cookie(config.tokencookie, token, cookieOptions);
        res.redirect(req.body.returnUrl);
      } else {
        // res.render("login/error", {
        //   title: "登录错误",
        //   message: "该手机号尚未注册",
        // });
        res.json({
          title: "登录错误",
          message: "该手机号尚未注册",
        });
      }
    }
  });

  router.post("/send_verifycode", async (req, res, next) => {
    console.log({ send_verifycode: req.body });
    let result = await send_verifycode(req.body.phone);
    res.json(result);
  });

  async function send_verifycode(phone) {
    let code = Math.round(Math.random() * 1000000);
    code = code.toString().slice(0, 4);
    console.log({ send_verifycode: code });

    // 验证码写入redis
    let key = "verifycode:".concat(phone);
    await ddd.setRedis(key, code);

    return send_sms({ code, phone });
  }

  function send_sms(p = {}) {
    let sendSmsRequest = new dysms.SendSmsRequest({
      signName: p.signName || "上海新舶科技",
      templateCode: p.templateCode || "SMS_296280451",
      phoneNumbers: p.phone,
      templateParam: JSON.stringify({ code: p.code }),
    });
    return smsClient.sendSms(sendSmsRequest);
  }

  function tokenCreate() {
    return uuid.v4().replace(/-/g, "");
  }

  return router;
};
